#include<stdio.h>
#include<stdlib.h>
#include<sys/mman.h>
#include<string.h>
#include<errno.h>
#include<unistd.h>
#include<fcntl.h>

void output(char *addr,int len)
{
	int i;
	for (i = 0; i < len; i++)
		printf("%c",addr[i]);
}

int main()
{
	int len = 1024;
	int fd = open("mmap.c",O_RDONLY);
	if (fd < 0)
	{
		perror("open error");
		exit(1);
	}
	//void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset);
	char *addr = (char *)mmap((void *)(0xb3ffffff) ,len,PROT_READ, MAP_PRIVATE,fd,0);
	printf("%p\n",addr);
	if (addr == MAP_FAILED)
	{
		perror("mmap error");
		exit(2);
	}
	output(addr, len);
	munmap(addr, len);
	/* 匿名映射 MAP_ANONYMOUS, The fd and offset  arguments are  ignored */
	addr = (char *)mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
	printf("%p\n",addr);
	if (addr == MAP_FAILED)
	{
		perror("mmap error");
		exit(2);
	}
	int i;
	for (i = 0; i < len; i++) addr[i] = i % 10 + 60;
	output(addr, len);
	munmap(addr, len);
	
	return 0;
}
